package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {

    private String method;
    private String uri;
    private String protocol;
    private  Socket socket;
    private String requestURI;

    private String queryString;
    private Map<String,String> parameters = new HashMap<>();

    private Map<String,String> handles = new HashMap<>();
    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket = socket;

        parseRequestLine();
        parseHeaders();
        parseContent();
    }

    private void parseRequestLine() throws IOException,EmptyRequestException{
        String line =readLine();
        if(line.isEmpty()){
            throw new EmptyRequestException();
        }
        System.out.println("请求行内容"+line);

        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        paresURI();
        System.out.println("method；"+method+"\tuir："+uri+"\tprotocol："+protocol);
    }

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char pro ='a',cur ='a';
        int d;
        while ((d = in.read())!=-1){
            cur = (char)d;
            if(pro==13&&cur==10){
                break;
            }
            builder.append(cur);
            pro = cur;
        }
        return builder.toString().trim();
    }

    public void parseHeaders() throws IOException {
        while (true){
            String line =readLine();
            if (line.isEmpty()){
                break;
            }
            System.out.println("头消息："+line);
            String[] data = line.split("\\s");
            handles.put(data[0],data[1]);
        }
        System.out.println("handles"+handles);

    }

    private void paresURI(){
        String[] data = uri.split("\\?");
        requestURI = data[0];
        if(data.length>1){
            queryString = data[1];

        }
    }

    private void parseParameters(String line){
        try {
            line = URLDecoder.decode(line,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] data = queryString.split("&");
        for (String para : data){
            String[] arr = para.split("=",2);
            parameters.put(arr[0],arr[1]);
        }
    }

    public void parseContent() throws IOException {
        if("post".equals(method)){
            if(handles.containsKey("Content-Length")){
                int contentLength = Integer.parseInt(handles.get("Content-Length"));
                byte[] bytes = new byte[contentLength];
                InputStream in = socket.getInputStream();
                in.read(bytes);
                String contentType = handles.get("Content-Type");
                if("application/x-www-form=urlencoded".equals(contentType)){
                    String line = new String(bytes,StandardCharsets.ISO_8859_1);
                    parseParameters(line);
                }

            }
        }
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHandles(String name) {
        return handles.get(name);
    }
    public String getRequestURI(){
        return  requestURI;
    }

    public String getParameter(String name) {
        return parameters.get(name);
    }
    public String getQueryString() {
        return queryString;
    }
}
